<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Encyclopedia\Article;
use App\Models\System\Region;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;

class RegionController extends Controller
{
    const REGION_S = [
        'ABC' => [],
        'DEF' => [],
        'GHI' => [],
        'JKL' => [],
        'MNO' => [],
        'PQR' => [],
        'STU' => [],
        'VWX' => [],
        'YZ'  => [],
    ];

    public function index()
    {
        $region = $this->region();
        $renovation = $this->renovation();
        $second = $this->second();
        return view('region', [
            'regions'    => $region,
            'renovation' => $renovation,
            'second'     => $second
        ]);
    }

    public function region()
    {
        $data = self::REGION_S;
        $region = Region::where('level', 2)->get();
        $region->each(function (Region $region) use (&$data) {
            foreach ($data as $key => $v) {
                if (strpos($key, strtoupper($region->initials)[0]) !== false) {
                    $region->path = 'http://' . $region->initials . '.' . env('URL_SUBSTATION', '');
                    $data[$key][] = $region;
                }
            }
        });
        $region = new Collection($data);
        return $region;
    }

    private function renovation()
    {
        $renovation = Article::inRandomOrder()->take(6)->get();
        $renovation = $renovation->map(function (Article $item) {
            $item->media->path = Storage::url($item->media->path);
            return $item;
        });
        return $renovation;
    }

    private function second()
    {
        $second = Article::inRandomOrder()->take(6)->get();
        $second = $second->map(function (Article $item) {
            $item->media->path = Storage::url($item->media->path);
            return $item;
        });
        return $second;
    }
}
